/*
Copyright (c) 2010 Bryce Alcock

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.com

 */

/*
 * NewJPanel.java
 *
 * Created on Oct 9, 2010, 1:30:52 PM
 */
package com.ecocrypt.proxy.forwarder.gui;

import com.ecocrypt.environment.Info;
import com.ecocrypt.proxy.forwarder.ClientServiceRequest;
import com.ecocrypt.proxy.forwarder.Forwarder;
import com.ecocrypt.proxy.forwarder.transfer.ForwarderListener;
import java.awt.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

/**
 *
 * @author bryce
 */
public class ForwarderPanelTop extends javax.swing.JPanel implements ForwarderListener, ListSelectionListener {

    Forwarder forwarder;
    ForwardPanelTableModel forwardTableModel;

    public void valueChanged(ListSelectionEvent e) {
        //System.out.println(" Value Changed. ");
        //System.out.println("Select changed to : " + jTable1.getSelectedRow());

        if (jTable1.getSelectedRow() > -1) {

            int selectedRow = jTable1.getSelectedRow();



            //  If we are in Java1.6 or higher, we are using the JVM's JTable Row Sorter.
            //  We will use reflection to dynamically invoke the Row Conversion method.
            //  That method does not exist in Java versions before 1.6.
            if (Info.isMinVersion()) {
                Class partypes[] = new Class[1];
                partypes[0] = Integer.TYPE;
                Object arglist[] = new Object[1];
                arglist[0] = selectedRow;
                try {
                    // Future Enhancement.
                    //  This method object could be Cached for performance improvements.
                    Method meth = jTable1.getClass().getMethod("convertRowIndexToModel", partypes);
                    selectedRow = (Integer) meth.invoke(jTable1, arglist);

                } catch (IllegalAccessException ex) {
                    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchMethodException ex) {
                    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            ForwardPanelTableModel fptm = (ForwardPanelTableModel) jTable1.getModel();
            ClientServiceRequest csr = fptm.getItemAt(selectedRow);
            requestDetailArea.setText(csr.toString());
        }
    }

    /** Creates new form NewJPanel */
    public ForwarderPanelTop(ForwardPanelTableModel fptm, Forwarder f) {
        forwardTableModel = fptm;
        forwarder = f;
        forwarder.register(this);

        initComponents();


        jTable1.getSelectionModel().addListSelectionListener(this);

        // Adding a single Cell Renderer for all the Columns.
        // the cell rednerer can switch on object type, and column id.
        ConnectionTableCellRenderer ctcr = new ConnectionTableCellRenderer();
        for (int i = 0; i < jTable1.getColumnCount(); ++i) {
            jTable1.getColumnModel().getColumn(i).setCellRenderer(ctcr);
        }

        // Using reflection to invoke the setAutoCreateRowSorter.
        // This method does not exits before java 1.6.
        if (Info.isMinVersion()) {
            Class partypes[] = new Class[1];
            partypes[0] = Boolean.TYPE;
            Object arglist[] = new Object[1];
            arglist[0] = Boolean.TRUE;
            try {
                Method meth = jTable1.getClass().getMethod("setAutoCreateRowSorter", partypes);
                meth.invoke(jTable1, arglist);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
                Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        // size the column widths the best that java can.
        initColumnSizes(jTable1);
    }

    String getTitle() {
        return forwarder.toString();
    }

    private void updateDynamicStats() {

        System.gc();

        activeField.setText(String.valueOf(forwarder.activeCount.get()));
        bytesInClient.setText(String.valueOf(forwarder.totalBytesFromClient.get()));
        bytesInEngine.setText(String.valueOf(forwarder.totalBytesFromEngine.get()));
        bytesOutClient.setText(String.valueOf(forwarder.totalBytesToClient.get()));
        bytesOutEngine.setText(String.valueOf(forwarder.totalBytesToEngine.get()));
        errorsField.setText(String.valueOf(forwarder.errorCount.get()));
        successField.setText(String.valueOf(forwarder.currentRequestId.get()));
        long freemem = Runtime.getRuntime().freeMemory();
        freemem = (long) freemem / 1024 / 1024;
        long mbTotalTable = (long) forwardTableModel.getTotalSize() / 1024 / 1024;
        long mbCompletedTable = (long) forwardTableModel.getCompletedSize() / 1024 / 1024;
        statusField.setText(freemem + " MB free");
        tableSizes.setText(String.format("[%d MB] %d MB ", mbCompletedTable, mbTotalTable));
        System.gc();

    }

    public void connectionAdded(Forwarder source) {

        updateDynamicStats();

    }

    public void connectionRemoved(Forwarder source, ClientServiceRequest csr) {

        updateDynamicStats();

    }

    public void connectionDataChanged(Forwarder source, ClientServiceRequest csr) {

        updateDynamicStats();

    }

    public void forwarderDynamicStateChanged(Forwarder source) {

	//System.out.println("Forwarder Dynamic state changed"+this.getClass().getName());
        updateDynamicStats();

    }

    //--------------------------------------------------------------------------
    // Additional Licence Related oracle:  CODE MODIFIED BY 47906 PROXY.
    /*
        * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
        *
        * Redistribution and use in source and binary forms, with or without
        * modification, are permitted provided that the following conditions
        * are met:
        *
        *   - Redistributions of source code must retain the above copyright
        *     notice, this list of conditions and the following disclaimer.
        *
        *   - Redistributions in binary form must reproduce the above copyright
        *     notice, this list of conditions and the following disclaimer in the
        *     documentation and/or other materials provided with the distribution.
        *
        *   - Neither the name of Oracle or the names of its
        *     contributors may be used to endorse or promote products derived
        *     from this software without specific prior written permission.
        *
        * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
        * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
        * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
        * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
        * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
        * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
        * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
        * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
        * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        */

   /*
     * This method picks good column sizes.
     * If all column heads are wider than the column's cells'
     * contents, then you can just use column.sizeWidthToFit().
     */
    private void initColumnSizes(JTable table) {
        ForwardPanelTableModel model = (ForwardPanelTableModel)table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer =
            table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                             getTableCellRendererComponent(
                                 table, longValues[i],
                                 false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;


            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }
    //  END CODE TAKEN FROM ORACLE/Java.
    //--------------------------------------------------------------------------

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        statusPanel = new javax.swing.JPanel();
        activeLable = new javax.swing.JLabel();
        errorsLable = new javax.swing.JLabel();
        successLable = new javax.swing.JLabel();
        statusField = new javax.swing.JLabel();
        bytesIn = new javax.swing.JLabel();
        bytesOut = new javax.swing.JLabel();
        activeField = new javax.swing.JTextField();
        errorsField = new javax.swing.JTextField();
        successField = new javax.swing.JTextField();
        engineLable = new javax.swing.JLabel();
        bytesInEngine = new javax.swing.JTextField();
        bytesOutEngine = new javax.swing.JTextField();
        toggleActiveComplete = new javax.swing.JToggleButton();
        freezeToggleButton = new javax.swing.JToggleButton();
        tableSizes = new javax.swing.JLabel();
        clientLable = new javax.swing.JLabel();
        bytesOutClient = new javax.swing.JTextField();
        bytesInClient = new javax.swing.JTextField();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        requestDetailArea = new javax.swing.JTextArea();

        setLayout(new java.awt.BorderLayout());

        statusPanel.setLayout(new java.awt.GridLayout(3, 7));

        activeLable.setText("Active");
        statusPanel.add(activeLable);

        errorsLable.setText("Errors");
        statusPanel.add(errorsLable);

        successLable.setText("Success");
        statusPanel.add(successLable);

        statusField.setText("statusField");
        statusPanel.add(statusField);

        bytesIn.setText("Bytes In");
        statusPanel.add(bytesIn);

        bytesOut.setText("Bytes Out");
        statusPanel.add(bytesOut);

        activeField.setText("0");
        statusPanel.add(activeField);

        errorsField.setText("0");
        statusPanel.add(errorsField);

        successField.setText("0");
        statusPanel.add(successField);

        engineLable.setText("Engine");
        statusPanel.add(engineLable);

        bytesInEngine.setText("0");
        statusPanel.add(bytesInEngine);

        bytesOutEngine.setText("0");
        statusPanel.add(bytesOutEngine);

        toggleActiveComplete.setText("Active");
        toggleActiveComplete.setToolTipText("Press to Toggle Active Connections \nvs complted connections.");
        toggleActiveComplete.setActionCommand("toggleActive");
        toggleActiveComplete.setMargin(new java.awt.Insets(3, 3, 3, 3));
        toggleActiveComplete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toggleActiveCompleteActionPerformed(evt);
            }
        });
        statusPanel.add(toggleActiveComplete);

        freezeToggleButton.setText("Freeze");
        freezeToggleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                freezeToggleButtonActionPerformed(evt);
            }
        });
        statusPanel.add(freezeToggleButton);
        statusPanel.add(tableSizes);

        clientLable.setText("Client");
        statusPanel.add(clientLable);

        bytesOutClient.setText("0");
        statusPanel.add(bytesOutClient);

        bytesInClient.setText("0");
        statusPanel.add(bytesInClient);

        add(statusPanel, java.awt.BorderLayout.NORTH);

        jSplitPane1.setDividerLocation(50);
        jSplitPane1.setDividerSize(4);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setLastDividerLocation(50);

        jTable1.setModel(forwardTableModel);
        jScrollPane1.setViewportView(jTable1);

        jSplitPane1.setLeftComponent(jScrollPane1);

        requestDetailArea.setColumns(20);
        requestDetailArea.setRows(5);
        jScrollPane2.setViewportView(requestDetailArea);

        jSplitPane1.setRightComponent(jScrollPane2);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void toggleActiveCompleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toggleActiveCompleteActionPerformed
        forwardTableModel.isActive = !forwardTableModel.isActive;
        if (forwardTableModel.isActive) {
            toggleActiveComplete.setText("Active");
        } else {
            toggleActiveComplete.setText("Completed");
        }
        forwardTableModel.fireTableDataChanged();
    }//GEN-LAST:event_toggleActiveCompleteActionPerformed

    private void freezeToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_freezeToggleButtonActionPerformed
        forwardTableModel.isFrozen = !forwardTableModel.isFrozen;
        if (forwardTableModel.isFrozen) {
            freezeToggleButton.setText("Release");
        } else {
            freezeToggleButton.setText("Freeze");
        }
    }//GEN-LAST:event_freezeToggleButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField activeField;
    private javax.swing.JLabel activeLable;
    private javax.swing.JLabel bytesIn;
    private javax.swing.JTextField bytesInClient;
    private javax.swing.JTextField bytesInEngine;
    private javax.swing.JLabel bytesOut;
    private javax.swing.JTextField bytesOutClient;
    private javax.swing.JTextField bytesOutEngine;
    private javax.swing.JLabel clientLable;
    private javax.swing.JLabel engineLable;
    private javax.swing.JTextField errorsField;
    private javax.swing.JLabel errorsLable;
    private javax.swing.JToggleButton freezeToggleButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea requestDetailArea;
    private javax.swing.JLabel statusField;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField successField;
    private javax.swing.JLabel successLable;
    private javax.swing.JLabel tableSizes;
    private javax.swing.JToggleButton toggleActiveComplete;
    // End of variables declaration//GEN-END:variables
}
